package com.ymatou.query.seller.trading.api.parameter.SellerApp;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ymatou.query.seller.trading.api.parameter.Sp_GetAppSellerOrdersByOrderIds;
import com.ymatou.query.seller.trading.api.parameter.AppResponse.SellerOrderInfoDetail;
import com.ymatou.query.seller.trading.api.parameter.AppResponse.SellerOrderProductInfo;
import com.ymatou.query.trading.api.parameter.OrderConverter;
import com.ymttest.common.entitie.SellerOrderInfoV3;
import com.ymttest.database.model.ProductPromotion;
import com.ymttest.utils.DataUtil;

public class Common {

	public static List<SellerOrderInfoV3> GetAppSellerOrdersFromDB(
			Sp_GetAppSellerOrdersByOrderIds sp, boolean detail) {
		GetSellerOrdersListV3Result result = ConvertResult(sp);
		if (DataUtil.isNullOrEmpty(result.getOrderInfos())) {
			return null;
		}
		List<SellerOrderInfoV3> orders = new ArrayList<SellerOrderInfoV3>();
		for (GetSellerOrdersListV3Result.OrderInfo order : result
				.getOrderInfos()) {
			orders.add(GetOrderInfo(order, result.getProductInfos().stream()
					.filter(x -> x.getiOrderId() == order.getiOrderId())
					.collect(Collectors.toList()), detail));
		}
		return orders;
	}

	@SuppressWarnings({"rawtypes", "unchecked"})
	private static GetSellerOrdersListV3Result ConvertResult(
			Sp_GetAppSellerOrdersByOrderIds sp) {
		GetSellerOrdersListV3Result result = new GetSellerOrdersListV3Result();
		List<GetSellerOrdersListV3Result.OrderInfo> orderInfos = new ArrayList<GetSellerOrdersListV3Result.OrderInfo>();
		List<GetSellerOrdersListV3Result.ProductInfo> productInfos = new ArrayList<GetSellerOrdersListV3Result.ProductInfo>();
		if (DataUtil.isNullOrEmpty(sp.getOrders()) == false) {
			for (Map m : sp.getOrders()) {
				GetSellerOrdersListV3Result.OrderInfo o = new GetSellerOrdersListV3Result.OrderInfo();
				m.put("buyerInBlacklist",
						DataUtil.int2Bool((int) m.get("buyerInBlacklist")));
				DataUtil.mapToBean(o, m);
				orderInfos.add(o);
			}
		}
		if (DataUtil.isNullOrEmpty(sp.getOrderInfos()) == false) {
			for (Map m : sp.getOrderInfos()) {
				GetSellerOrdersListV3Result.ProductInfo o = new GetSellerOrdersListV3Result.ProductInfo();
				if (m.get("PromotionId") != null) {
					o.setPromotionId((int) m.get("PromotionId"));
					o.setPromotionName(DataUtil.Stringg.getValueOrNull(m
							.get("PromotionName")));
					o.setPromotionType(DataUtil.Integerr.GetValueOrNull(m
							.get("PromotionType")));
					o.setPromotionValue(DataUtil.Stringg.getValueOrNull(m
							.get("PromotionValue")));
					o.setMatchCondition(DataUtil.Stringg.getValueOrNull(m
							.get("MatchCondition")));
					o.setReducedAmount(DataUtil.BigDecimall.GetValueOrNull(m
							.get("ReducedAmount")));
				}
				DataUtil.mapToBean(o, m);
				productInfos.add(o);
			}
		}
		result.setOrderInfos(orderInfos);
		result.setProductInfos(productInfos);
		return result;
	}

	private static SellerOrderInfoV3 GetOrderInfo(
			GetSellerOrdersListV3Result.OrderInfo order,
			List<GetSellerOrdersListV3Result.ProductInfo> products,
			boolean detail) {
		SellerOrderInfoV3 o = detail
				? new SellerOrderInfoDetail()
				: new SellerOrderInfoV3();

		o.setOrderGroupId(order.getiMainOrderId());
		o.setOrderId(order.getiOrderId());
		o.setOrderStatus(order.getiTradingStatus());
		o.setRiskVerifiedStatus(order.getiRiskVerifiedStatus());
		o.setBuyerUserId(order.getiUserId());
		o.setCreateOrderDate(DataUtil.Stringg.getValueOrDefault(order
				.getdAddTime()));
		o.setBuyerUserLoginId(order.getsBuyerLoginId());
		o.setLeaveWord(order.getsLeaveWord());
		o.setPaidInFull(order.isbPaidInFull());
		o.setSellerNote(order.getSellerNote());

		o.setApplyPostPayTime(order.getdApplyPostPayTime());
		o.setPaidTime(order.getdPaidTime());
		o.setPostpayTime(order.getdPostPaidTime());
		o.setDeliveryTime(order.getdDispathTime());
		o.setOrderCancelledTime(order.getdCancelTime());
		o.setOrderConfirmedTime(order.getdConfirmedTime());

		o.setFreight(order.getfFreight());
		o.setNeedUploadIdCard(order.isbIsNeedUploadIdCard());
		o.setHaveUploadedIdCard(order.isbHaveUploadedIdCard());
		o.setIsNewCustomerOrder(order.isbNewCustomerOrder());
		o.setIsNewSellerOrder(order.isbNewSellerOrder());

		if (detail) {
			SellerOrderInfoDetail d = (SellerOrderInfoDetail) o;
			d.setOrderCancelReason(order.getsCancelReason());
			d.setRecipientName(order.getsReceivePerson());
			d.setMobile(order.getsPhone());
			d.setZipCode(order.getsPostCode());
			d.setAddress(order.getsAddress());
		}

		// 是否只需支付一次
		o.setOnlyNeedPayOnce(!order.isbShangouOrder());

		// 活动优惠金额
		o.setSellerPromotionAmount(order.getfSellerPromotionAmount());
		// 优惠券
		BigDecimal couponAmount = SetCouponInfoAndReturnTotalCouponAmount(o,
				order);

		o.setBuyerInBlacklist(order.isBuyerInBlacklist());

		o.setFreight(order.getfFreight());
		o.setGiftAmount(DataUtil.BigDecimall.add(order.getfUseGiftAmount(),
				order.getPostpayUseGiftAmount()));

		//新交易下单，没有需要补款订单

		/*	if (order.isbShangouOrder()) // C
			{
				o.setTotalProductPrice(order.getfTotalPrice());
				BigDecimal price = DataUtil.BigDecimall
						.GetValueOrDefault(order.getfOrderPrice())
						.add(DataUtil.BigDecimall.GetValueOrDefault(o.getFreight()))
						.add(DataUtil.BigDecimall.GetValueOrDefault(order
								.getfOrderDiscount()))
						.subtract(
								DataUtil.BigDecimall
										.GetValueOrDefault(couponAmount))
						.subtract(
								DataUtil.BigDecimall.GetValueOrDefault(order
										.getfUseGiftAmount()))
						.subtract(
								DataUtil.BigDecimall.GetValueOrDefault(order
										.getfSellerPromotionAmount()));
				o.setExpectedPayAmount(price.compareTo(new BigDecimal(0)) > 0
						? price
						: new BigDecimal(0));
				BigDecimal c = DataUtil.BigDecimall.subtract(
						order.getfTotalPrice(), order.getfOrderPrice());
				o.setOriginalPostpayAmount(c);
				if (order.isbPaidInFull()) {
					o.setExpectedPostpayAmount(DataUtil.BigDecimall
							.GetValueOrDefault(order.getPostpayAmount()));
				} else {
					if (order.getPostpayAmount() == null) {
						o.setExpectedPostpayAmount(o.getOriginalPostpayAmount());
					} else {
						o.setExpectedPostpayAmount(order.getPostpayAmount());
					}
				}

				o.setDiscount(DataUtil.BigDecimall
						.GetValueOrDefault(order.getfOrderDiscount())
						.add(DataUtil.BigDecimall.GetValueOrDefault(o
								.getExpectedPostpayAmount()))
						.subtract(
								DataUtil.BigDecimall.GetValueOrDefault(o
										.getOriginalPostpayAmount())));

				if (order.getPostpayUseGiftAmount() != null) {
					BigDecimal t = DataUtil.BigDecimall.subtract(
							o.getExpectedPostpayAmount(),
							order.getPostpayUseGiftAmount());

				}

				o.setExpectedTotalPayAmount(DataUtil.BigDecimall.add(
						o.getExpectedPayAmount(), o.getExpectedPostpayAmount()));
			} else // M
			{*/
		o.setExpectedPostpayAmount(BigDecimal.ZERO);
		o.setTotalProductPrice(order.getfTotalPrice());
		o.setDiscount(order.getfOrderDiscount());
		BigDecimal t = o.getTotalProductPrice().add(o.getDiscount())
				.add(o.getFreight())
				.subtract(DataUtil.BigDecimall.GetValueOrDefault(couponAmount))
				.subtract(o.getGiftAmount())
				.subtract(o.getSellerPromotionAmount());

		o.setExpectedPayAmount(t.compareTo(new BigDecimal(0)) > 0
				? t
				: new BigDecimal(0));
		o.setExpectedTotalPayAmount(o.getExpectedPayAmount());

		//}

		if (DataUtil.isNullOrEmpty(products))
			return o;

		o.setProducts(GetOrderProducts(order, products));

		return o;
	}

	private static List<SellerOrderProductInfo> GetOrderProducts(
			GetSellerOrdersListV3Result.OrderInfo order,
			List<GetSellerOrdersListV3Result.ProductInfo> products) {
		List<SellerOrderProductInfo> result = new ArrayList<SellerOrderProductInfo>();
		if (DataUtil.isNullOrEmpty(products) == false) {
			for (GetSellerOrdersListV3Result.ProductInfo x : products) {
				SellerOrderProductInfo o = new SellerOrderProductInfo();
				o.setProductPictureUrl(DataUtil.Stringg.getValueOrDefault(x
						.getsPictureUrl()));
				o.setPropertyInfo(DataUtil.Stringg.getValueOrDefault(x
						.getsPropertyInfo()));
				o.setProductId(DataUtil.Stringg.getValueOrDefault(x
						.getsProductId()));
				o.setProductTitle(DataUtil.Stringg.getValueOrDefault(x
						.getsTitle()));
				o.setCatalogId(DataUtil.Stringg.getValueOrDefault(x
						.getsCatalogId()));
				o.setCatalogStatus(DataUtil.Integerr.GetValueOrNull(x
						.getiCatalogStatus()));
				o.setProductPrice(x.getfProductPrice());
				o.setProductOriginalPrice(x.getfProductOriginalPrice());
				o.setProductNum(x.getiAmount());
				o.setCatalogType(x.getiCatalogType());
				o.setPriceType(x.getiPriceType());
				o.setLogisticsType(x.getiCatalogStatus());
				o.setProductRefundChannel(x.getiProductRefundChannel());
				o.setProductRefund(x.getiProductRefundStatus() != null
						&& x.getiProductRefundStatus() != 0);
				o.setSalesRefundCode(x.getSalesRefundCode());
				o.setSalesRefundStatus(DataUtil.Integerr.GetValueOrDefault(x
						.getiProductRefundStatus()));
				o.setSalesRefundAmount(x.getSalesRefundAmount());
				o.setCouponAmount(x.getfYmtCouponAmount());
				o.setSellerCouponAmount(x.getfSellerCouponAmount());
				o.setFreightPartialAmount(x.getfFreight());
				o.setDiscountPartialAmount(x.getfDiscount());
				o.setTariffType(x.getiTariffType());
				o.setFreightFree(x.getbFreightFree());
				o.setSupportRtnWithoutReason(x.isbSupportRtnWithoutReason());

				o.setPspProduct(x.isbPspProduct());

				com.ymatou.query.seller.trading.api.parameter.Ymt_OrderInfo info = new com.ymatou.query.seller.trading.api.parameter.Ymt_OrderInfo();
				info.setfSellerPromotionAmount(x.getfSellerPromotionAmount());
				info.setPromotionId(x.getPromotionId());
				info.setPromotionType(x.getPromotionType());
				info.setPromotionName(x.getPromotionName());
				info.setMatchCondition(x.getMatchCondition());
				info.setPromotionValue(x.getPromotionValue());
				info.setReducedAmount(x.getReducedAmount());
				ProductPromotion promotion = OrderConverter.GetPromotion(info);
				o.setPromotion(promotion);

				result.add(o);
			}
		}
		return result;
	}

	private static BigDecimal SetCouponInfoAndReturnTotalCouponAmount(
			SellerOrderInfoV3 o, GetSellerOrdersListV3Result.OrderInfo order) {
		if (DataUtil.BigDecimall.compare0(order.getfYmtCouponAmount()) > 0
				|| DataUtil.BigDecimall
						.compare0(order.getfSellerCouponAmount()) > 0) {
			o.setCouponCode(order.getsYmtCouponCode());
			o.setCouponAmount(order.getfYmtCouponAmount());

			o.setSellerCouponCode(order.getsSellerCouponCode());
			o.setSellerCouponAmount(order.getfSellerCouponAmount());

			return DataUtil.BigDecimall.add(order.getfYmtCouponAmount(),
					order.getfSellerCouponAmount());
		}

		BigDecimal couponAmount = DataUtil.BigDecimall.GetValueOrDefault(order
				.getCouponValue());
		if (DataUtil.BigDecimall.compare0(couponAmount) > 0) {
			if (order.getiCouponChannel() == 2) {
				o.setSellerCouponAmount(couponAmount);
				o.setSellerCouponCode(order.getsCouponCode());
			} else {
				o.setCouponAmount(couponAmount);
				o.setCouponCode(order.getsCouponCode());
			}
		}
		return couponAmount;
	}
}
